/**
 * API服务层 - 业务逻辑封装
 * 提供高级API调用方法，包含错误处理和数据转换
 */

import { showToast, showSuccessToast, showLoadingToast, closeToast } from 'vant';
import { http } from '@/utils/request';
import {
  login,
  register,
  sendVerificationCode,
  getUserProfile,
  getBanners,
  getFunctions,
  getRecommendations,
  getActivities,
  getCourseCategories,
  getRecommendedCourses,
  searchCourses,
  getDetectionTexts,
  submitVoiceEvaluation,
  getDetectionHistory,
  getGameContents,
  submitGameResult,
  getGameRecords,
  getDailySentence,
  submitDailyReading,
  getDailyHistory,
  getNotifications,
  markNotificationRead,
  getStudyStatistics,
  getUserStatistics,
  uploadFile,
  uploadAudio,
  uploadVideo,
  type LoginRequest,
  type RegisterRequest,
  type PaginationParams,
  type ApiResponse,
  type UserInfo
} from './index';

/**
 * 通用错误处理
 */
function handleApiError(error: any, defaultMessage: string = '操作失败') {
  console.error('API Error:', error);
  const message = error.response?.data?.message || error.message || defaultMessage;
  showToast(message);
  return null;
}

/**
 * 通用加载处理
 */
async function withLoading<T>(
  apiCall: () => Promise<T>,
  loadingText: string = '加载中...'
): Promise<T | null> {
  try {
    showLoadingToast(loadingText);
    const result = await apiCall();
    closeToast();
    return result;
  } catch (error) {
    closeToast();
    throw error;
  }
}

// ==================== 用户认证服务 ====================

export class AuthService {
  /**
   * 用户登录
   */
  static async login(data: LoginRequest): Promise<{
    token: string;
    refreshToken: string;
    expiresIn: number;
    userInfo: UserInfo;
  } | null> {
    try {
      // 响应拦截器已经处理了业务状态码，这里获取响应数据
      const response = await withLoading(
        () => login(data),
        '登录中...'
      ) as any;

      if (response?.data?.data) {
        showToast('登录成功');
        return response.data.data;
      } else {
        showToast('登录失败');
        return null;
      }
    } catch (error) {
      return handleApiError(error, '登录失败');
    }
  }

  /**
   * 发送验证码
   */
  static async sendVerificationCode(phone: string) {
    try {
      const response = await sendVerificationCode({ phone });

      if (response?.data.code === 200) {
        showToast('验证码已发送');
        return response.data.data;
      } else {
        showToast(response?.data.message || '发送验证码失败');
        return null;
      }
    } catch (error) {
      return handleApiError(error, '发送验证码失败');
    }
  }

  /**
   * 用户注册
   */
  static async register(data: RegisterRequest) {
    try {
      const response = await withLoading(
        () => register(data),
        '注册中...'
      );
      
      if (response?.data.code === 200) {
        showToast('注册成功');
        return true;
      } else {
        showToast(response?.data.message || '注册失败');
        return false;
      }
    } catch (error) {
      handleApiError(error, '注册失败');
      return false;
    }
  }

  /**
   * 获取用户信息
   */
  static async getUserProfile() {
    try {
      const response = await getUserProfile();
      if (response.data.code === 200) {
        return response.data.data;
      }
      return null;
    } catch (error) {
      return handleApiError(error, '获取用户信息失败');
    }
  }
}

// ==================== 首页服务 ====================

export class HomeService {
  /**
   * 加载首页所有数据
   */
  static async loadHomeData() {
    try {
      showLoadingToast('加载中...');
      
      const [bannersRes, functionsRes, recommendationsRes, activitiesRes] = await Promise.all([
        getBanners(),
        getFunctions(),
        getRecommendations({ page: 1, limit: 10 }),
        getActivities()
      ]);

      closeToast();

      return {
        banners: bannersRes.data.code === 200 ? bannersRes.data.data : [],
        functions: functionsRes.data.code === 200 ? functionsRes.data.data : [],
        recommendations: recommendationsRes.data.code === 200 ? recommendationsRes.data.data.list : [],
        activities: activitiesRes.data.code === 200 ? activitiesRes.data.data : []
      };
    } catch (error) {
      closeToast();
      handleApiError(error, '首页数据加载失败');
      return {
        banners: [],
        functions: [],
        recommendations: [],
        activities: []
      };
    }
  }

  /**
   * 获取轮播图
   */
  static async getBanners() {
    try {
      const response = await getBanners();
      return response.data.code === 200 ? response.data.data : [];
    } catch (error) {
      return handleApiError(error, '获取轮播图失败') || [];
    }
  }

  /**
   * 获取推荐内容
   */
  static async getRecommendations(params: PaginationParams) {
    try {
      const response = await getRecommendations(params);
      return response.data.code === 200 ? response.data.data : { list: [], total: 0 };
    } catch (error) {
      return handleApiError(error, '获取推荐内容失败') || { list: [], total: 0 };
    }
  }
}

// ==================== 学习中心服务 ====================

export class StudyService {
  /**
   * 获取课程分类
   */
  static async getCategories() {
    try {
      const response = await http.get('/study/categories');
      console.log('✅ 课程分类API响应:', response.data);
      return response.data;
    } catch (error) {
      handleApiError(error, '获取课程分类失败');
      return { data: [] };
    }
  }

  /**
   * 获取推荐课程列表
   */
  static async getRecommendedCourses(params: {
    page?: number;
    limit?: number;
    category?: number;
    difficulty?: string;
  } = {}) {
    try {
      const response = await http.get('/study/courses/recommended', { params });
      return response.data;
    } catch (error) {
      handleApiError(error, '获取推荐课程失败');
      return { data: { list: [], total: 0, page: 1, limit: 20, totalPages: 0 } };
    }
  }

  /**
   * 搜索课程
   */
  static async searchCourses(keyword: string, params: {
    page?: number;
    limit?: number;
    category?: string;
    difficulty?: string;
  } = {}) {
    try {
      const searchParams = {
        keyword,
        page: params.page || 1,
        limit: params.limit || 20,
        category: params.category,
        difficulty: params.difficulty
      };
      const response = await searchCourses(searchParams);
      return response.data;
    } catch (error) {
      handleApiError(error, '搜索课程失败');
      return { data: { courses: [], pagination: {} } };
    }
  }

  /**
   * 获取课程详情（核心接口）
   */
  static async getCourseDetail(courseId: number) {
    try {
      const response = await http.get(`/study/courses/${courseId}`);
      return response.data;
    } catch (error) {
      handleApiError(error, '获取课程详情失败');
      return null;
    }
  }

  /**
   * 获取课程的课时列表
   */
  static async getCourseLessons(courseId: number, params: {
    chapter_id?: number;
  } = {}) {
    try {
      const response = await http.get(`/courses/${courseId}/lessons`, { params });
      return response.data;
    } catch (error) {
      handleApiError(error, '获取课时列表失败');
      return { data: [] };
    }
  }

  /**
   * 获取课时详情
   */
  static async getLessonDetail(courseId: number, lessonId: number) {
    try {
      const response = await http.get(`/courses/${courseId}/lessons/${lessonId}`);
      return response.data;
    } catch (error) {
      handleApiError(error, '获取课时详情失败');
      return null;
    }
  }

  /**
   * 获取用户课程列表
   */
  static async getMyCourses(params: {
    page?: number;
    limit?: number;
    status?: string;
  } = {}) {
    try {
      const response = await http.get('/study/my-courses', { params });
      return response.data;
    } catch (error) {
      handleApiError(error, '获取我的课程失败');
      return { data: { courses: [], pagination: {} } };
    }
  }

  /**
   * 检查用户是否已报名课程
   */
  static async checkEnrollmentStatus(courseId: number) {
    try {
      const response = await http.get(`/study/courses/${courseId}/enrollment-status`);
      console.log('✅ 检查报名状态成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ 检查报名状态失败:', error);
      handleApiError(error, '检查报名状态失败');
      return null;
    }
  }

  /**
   * 课程报名
   */
  static async enrollCourse(courseId: number) {
    try {
      const response = await http.post(`/study/courses/${courseId}/enroll`);
      showSuccessToast('报名成功');
      console.log('✅ 课程报名成功:', response.data);
      return response.data;
    } catch (error) {
      handleApiError(error, '课程报名失败');
      return null;
    }
  }

  /**
   * 更新学习进度 (兼容旧接口)
   */
  static async updateProgress(courseId: number, progressData: {
    lesson_id: number;
    progress: number;
    watch_time: number;
    is_completed: boolean;
  }) {
    try {
      const response = await http.put(`/study/courses/${courseId}/progress`, progressData);
      return response.data;
    } catch (error) {
      handleApiError(error, '更新学习进度失败');
      return null;
    }
  }

  /**
   * 更新课时观看进度 (新接口)
   */
  static async updateLessonProgress(courseId: number, lessonId: number, progressData: {
    progress?: number;        // 观看进度百分比 (0-100)
    watch_time?: number;      // 本次观看时长(秒)
    current_position?: number; // 当前播放位置(秒)
  }) {
    try {
      const response = await http.put(`/study/courses/${courseId}/lessons/${lessonId}/progress`, progressData);
      console.log('✅ 课时进度更新成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ 课时进度更新失败:', error);
      handleApiError(error, '更新课时进度失败');
      return null;
    }
  }

  /**
   * 获取课时观看进度
   */
  static async getLessonProgress(courseId: number, lessonId: number) {
    try {
      const response = await http.get(`/study/courses/${courseId}/lessons/${lessonId}/progress`);
      console.log('✅ 获取课时进度成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ 获取课时进度失败:', error);
      handleApiError(error, '获取课时进度失败');
      return null;
    }
  }

  /**
   * 获取课程整体进度
   */
  static async getCourseProgress(courseId: number) {
    try {
      const response = await http.get(`/study/courses/${courseId}/progress`);
      console.log('✅ 获取课程进度成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ 获取课程进度失败:', error);
      handleApiError(error, '获取课程进度失败');
      return null;
    }
  }

  /**
   * 标记课时为已完成
   */
  static async markLessonCompleted(courseId: number, lessonId: number) {
    try {
      const response = await http.put(`/study/courses/${courseId}/lessons/${lessonId}/complete`);
      console.log('✅ 标记课时完成成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ 标记课时完成失败:', error);
      handleApiError(error, '标记课时完成失败');
      return null;
    }
  }

  /**
   * 获取用户学习统计数据
   */
  static async getLearningStats(params: {
    period?: 'day' | 'week' | 'month' | 'year' | 'all';
    startDate?: string;
    endDate?: string;
  } = {}) {
    try {
      const response = await http.get('/study/learning-stats', { params });
      console.log('✅ 获取学习统计成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ 获取学习统计失败:', error);
      handleApiError(error, '获取学习统计失败');
      return null;
    }
  }

  /**
   * 获取用户学习进度概览
   */
  static async getProgressOverview() {
    try {
      const response = await http.get('/study/progress-overview');
      console.log('✅ 获取学习概览成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ 获取学习概览失败:', error);
      handleApiError(error, '获取学习概览失败');
      return null;
    }
  }

  /**
   * 获取用户学习趋势数据
   */
  static async getLearningTrends(days: number = 30) {
    try {
      const response = await http.get('/study/learning-trends', {
        params: { days }
      });
      console.log('✅ 获取学习趋势成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ 获取学习趋势失败:', error);
      handleApiError(error, '获取学习趋势失败');
      return null;
    }
  }

  /**
   * 加载学习中心数据
   */
  static async loadStudyData() {
    try {
      showLoadingToast('加载中...');

      const [categoriesRes, coursesRes] = await Promise.all([
        this.getCategories(),
        this.getRecommendedCourses({ page: 1, limit: 20 })
      ]);

      closeToast();

      return {
        categories: categoriesRes.data || [],
        courses: coursesRes.data?.courses || []
      };
    } catch (error) {
      closeToast();
      handleApiError(error, '学习中心数据加载失败');
      return {
        categories: [],
        courses: []
      };
    }
  }


}

// ==================== 语音检测服务 ====================

export class DetectionService {
  /**
   * 获取检测文本
   */
  static async getDetectionTexts(filters?: { level?: string; category?: string }) {
    try {
      const response = await getDetectionTexts(filters);
      return response.data.code === 200 ? response.data.data : [];
    } catch (error) {
      return handleApiError(error, '获取检测文本失败') || [];
    }
  }

  /**
   * 提交语音评测
   */
  static async submitEvaluation(textId: number, audioFile: Blob, duration: number) {
    try {
      const formData = new FormData();
      formData.append('textId', textId.toString());
      formData.append('audioFile', audioFile, 'recording.wav');
      formData.append('duration', duration.toString());

      const response = await withLoading(
        () => submitVoiceEvaluation(formData),
        '分析中...'
      );

      if (response?.data.code === 200) {
        return response.data.data;
      } else {
        showToast(response?.data.message || '评测失败');
        return null;
      }
    } catch (error) {
      return handleApiError(error, '语音评测失败');
    }
  }

  /**
   * 获取评测历史
   */
  static async getHistory(params: PaginationParams) {
    try {
      const response = await getDetectionHistory(params);
      return response.data.code === 200 ? response.data.data : { list: [], total: 0 };
    } catch (error) {
      return handleApiError(error, '获取历史记录失败') || { list: [], total: 0 };
    }
  }
}

// ==================== 小游戏服务 ====================

export class GameService {
  /**
   * 获取游戏内容
   */
  static async getGameContents(filters?: { level?: string; category?: string }) {
    try {
      const response = await getGameContents(filters);
      return response.data.code === 200 ? response.data.data : [];
    } catch (error) {
      return handleApiError(error, '获取游戏内容失败') || [];
    }
  }

  /**
   * 提交游戏结果
   */
  static async submitGameResult(contentId: number, audioFile: Blob, duration: number) {
    try {
      const formData = new FormData();
      formData.append('contentId', contentId.toString());
      formData.append('audioFile', audioFile, 'game_recording.wav');
      formData.append('duration', duration.toString());

      const response = await withLoading(
        () => submitGameResult(formData),
        '分析中...'
      );

      if (response?.data.code === 200) {
        return response.data.data;
      } else {
        showToast(response?.data.message || '提交失败');
        return null;
      }
    } catch (error) {
      return handleApiError(error, '游戏结果提交失败');
    }
  }

  /**
   * 获取游戏记录
   */
  static async getGameRecords(params: PaginationParams) {
    try {
      const response = await getGameRecords(params);
      return response.data.code === 200 ? response.data.data : { list: [], total: 0 };
    } catch (error) {
      return handleApiError(error, '获取游戏记录失败') || { list: [], total: 0 };
    }
  }
}

// ==================== 每日一句服务 ====================

export class DailyService {
  /**
   * 获取每日一句
   */
  static async getDailySentence(date?: string) {
    try {
      const response = await getDailySentence(date ? { date } : undefined);
      return response.data.code === 200 ? response.data.data : null;
    } catch (error) {
      return handleApiError(error, '获取每日一句失败');
    }
  }

  /**
   * 上传音频文件
   */
  static async uploadAudio(audioFile: Blob, filename?: string) {
    try {
      console.log('DailyService.uploadAudio 开始执行');
      console.log('音频文件信息:', {
        size: audioFile.size,
        type: audioFile.type,
        filename: filename
      });

      // 验证文件类型 - 后端要求：mp3, wav, m4a
      const allowedTypes = [
        'audio/mp3',     // MP3格式
        'audio/mpeg',    // MP3格式的另一种MIME类型
        'audio/wav',     // WAV格式
        'audio/wave',    // WAV格式的另一种MIME类型
        'audio/m4a',     // M4A格式
        'audio/x-m4a',   // M4A格式的另一种MIME类型
        'audio/mp4'      // MP4音频格式（通常包含M4A）
      ];

      console.log('🔍 检查音频格式:', audioFile.type);

      if (!allowedTypes.includes(audioFile.type)) {
        console.warn('⚠️ 音频格式可能不被后端支持:', audioFile.type);
        console.log('📝 允许的格式:', allowedTypes);
        // 不阻止上传，让后端进行最终验证
      } else {
        console.log('✅ 音频格式验证通过:', audioFile.type);
      }

      // 验证文件大小 (10MB)
      const maxSize = 10 * 1024 * 1024;
      if (audioFile.size > maxSize) {
        console.log('文件过大:', audioFile.size);
        showToast('音频文件大小不能超过 10MB');
        return null;
      }

      console.log('文件验证通过，开始构建FormData');

      const formData = new FormData();
      const audioFilename = filename || `audio_${Date.now()}.${audioFile.type.split('/')[1]}`;
      formData.append('file', audioFile, audioFilename);

      console.log('FormData构建完成，开始发送请求');
      console.log('文件名:', audioFilename);

      const response = await withLoading(
        () => uploadAudio(formData),
        '上传中...'
      );

      console.log('上传请求响应:', response);

      if (response && response.data) {
        console.log('音频上传成功');
        showToast('音频上传成功');
        return response.data;
      } else {
        console.log('音频上传失败:', response);
        showToast('音频上传失败');
        return null;
      }
    } catch (error) {
      console.error('uploadAudio 异常:', error);
      return handleApiError(error, '音频上传失败');
    }
  }

  /**
   * 上传视频文件
   */
  static async uploadVideo(videoFile: File, filename?: string) {
    try {
      console.log('DailyService.uploadVideo 开始执行');
      console.log('视频文件信息:', {
        size: videoFile.size,
        type: videoFile.type,
        filename: filename
      });

      // 验证文件类型
      const allowedTypes = [
        'video/mp4',     // MP4格式
        'video/mov',     // MOV格式
        'video/avi',     // AVI格式
        'video/wmv',     // WMV格式
        'video/flv',     // FLV格式
        'video/webm',    // WebM格式
        'video/quicktime' // QuickTime格式
      ];

      console.log('🔍 检查视频格式:', videoFile.type);

      if (!allowedTypes.includes(videoFile.type)) {
        console.warn('⚠️ 视频格式可能不被后端支持:', videoFile.type);
        console.log('📝 允许的格式:', allowedTypes);
      } else {
        console.log('✅ 视频格式验证通过:', videoFile.type);
      }

      // 验证文件大小 (50MB)
      const maxSize = 50 * 1024 * 1024;
      if (videoFile.size > maxSize) {
        console.log('文件过大:', videoFile.size);
        showToast('视频文件大小不能超过 50MB');
        return null;
      }

      console.log('文件验证通过，开始构建FormData');

      const formData = new FormData();
      const videoFilename = filename || `video_${Date.now()}.${videoFile.type.split('/')[1]}`;
      formData.append('file', videoFile, videoFilename);

      console.log('FormData构建完成，开始发送请求');
      console.log('文件名:', videoFilename);

      const response = await withLoading(
        () => uploadVideo(formData),
        '上传中...'
      );

      console.log('📤 上传请求响应:', response);
      console.log('📤 响应数据结构:', response?.data);
      console.log('📤 响应数据类型:', typeof response?.data);

      if (response && response.data) {
        console.log('✅ 视频上传成功，返回数据:', response.data);
        showToast('视频上传成功');
        return response.data;
      } else {
        console.log('❌ 视频上传失败，响应为空或无数据:', response);
        showToast('视频上传失败');
        return null;
      }
    } catch (error) {
      console.error('uploadVideo 异常:', error);
      return handleApiError(error, '视频上传失败');
    }
  }

  /**
   * 提交每日一句记录
   */
  static async submitDailySentence(data: {
    sentenceId: number;
    videoUrl: string;
    submissionDate: string;
  }) {
    try {
      console.log('提交每日一句记录:', data);

      const response = await withLoading(
        () => submitDailyReading({
          sentenceId: data.sentenceId,
          videoUrl: data.videoUrl,
          submissionDate: data.submissionDate
        }),
        '提交中...'
      );

      if (response && response.data) {
        console.log('✅ 每日一句记录提交成功:', response);
        showToast('提交成功');
        return response.data;
      } else {
        console.log('❌ 每日一句记录提交失败:', response);
        showToast('提交失败');
        return null;
      }
    } catch (error) {
      console.error('❌ 每日一句记录提交失败:', error);
      return handleApiError(error, '提交失败');
    }
  }

  /**
   * 提交每日视频记录（包含视频URL和时长）
   */
  static async submitDailyVideo(data: {
    sentenceId: number;
    videoUrl: string;
    duration: number;
    submissionDate: string;
  }) {
    try {
      console.log('📝 开始提交每日视频记录:', data);

      const submitData = {
        sentenceId: data.sentenceId,
        videoUrl: data.videoUrl,
        duration: data.duration,
        submissionDate: data.submissionDate
      };

      console.log('📝 调用 submitDailyReading，参数:', submitData);

      const response = await withLoading(
        () => submitDailyReading(submitData),
        '提交中...'
      );

      console.log('📝 submitDailyReading 响应:', response);
      console.log('📝 响应数据结构:', response?.data);

      if (response && response.data) {
        console.log('✅ 每日视频记录提交成功:', response);
        showToast('提交成功');
        return response.data;
      } else {
        console.log('❌ 每日视频记录提交失败，响应为空或无数据:', response);
        showToast('提交失败');
        return null;
      }
    } catch (error) {
      console.error('❌ 每日视频记录提交异常:', error);
      return handleApiError(error, '提交失败');
    }
  }

  /**
   * 提交每日朗读 (支持FormData或参数形式)
   */
  static async submitDailyReading(data: FormData | { sentenceId: number, audioFile: Blob, duration: number }) {
    try {
      let formData: FormData;

      if (data instanceof FormData) {
        formData = data;
      } else {
        formData = new FormData();
        formData.append('sentenceId', data.sentenceId.toString());
        formData.append('audioFile', data.audioFile, 'daily_reading.webm');
        formData.append('duration', data.duration.toString());
      }

      const response = await withLoading(
        () => submitDailyReading(formData),
        '提交中...'
      );

      if (response && response.data) {
        showToast('提交成功');
        return response.data;
      } else {
        showToast('提交失败');
        return null;
      }
    } catch (error) {
      return handleApiError(error, '每日朗读提交失败');
    }
  }

  /**
   * 获取朗读历史
   */
  static async getDailyHistory(params: PaginationParams & { month?: string }) {
    try {
      console.log('📊 请求历史记录，参数:', params);
      const response: any = await getDailyHistory(params);
      console.log('📊 历史记录原始响应:', response);

      if (response && response.data && response.data.code === 200) {
        // 根据API响应结构，统计信息在 message.statistics 中
        const statistics = response.data.message?.statistics;
        const historyData = response.data.data;

        console.log('📊 解析的统计信息:', statistics);
        console.log('📊 解析的历史数据:', historyData);

        return {
          ...historyData,
          statistics: statistics
        };
      } else {
        console.log('❌ 历史记录响应格式错误:', response);
        return { list: [], total: 0, statistics: null };
      }
    } catch (error) {
      console.error('❌ 获取历史记录失败:', error);
      return handleApiError(error, '获取朗读历史失败') || { list: [], total: 0, statistics: null };
    }
  }
}

// ==================== 通知服务 ====================

export class NotificationService {
  /**
   * 获取通知列表
   */
  static async getNotifications(params: PaginationParams & { type?: string; status?: string }) {
    try {
      const response = await getNotifications(params);
      return response.data.code === 200 ? response.data.data : { list: [], total: 0, unreadCount: 0 };
    } catch (error) {
      return handleApiError(error, '获取通知失败') || { list: [], total: 0, unreadCount: 0 };
    }
  }

  /**
   * 标记通知已读
   */
  static async markAsRead(id: number) {
    try {
      const response = await markNotificationRead(id);
      return response.data.code === 200;
    } catch (error) {
      handleApiError(error, '标记已读失败');
      return false;
    }
  }
}

// ==================== 统计服务 ====================

export class StatisticsService {
  /**
   * 获取学习统计
   */
  static async getStudyStatistics(period?: string) {
    try {
      const response = await getStudyStatistics(period ? { period } : undefined);
      return response.data.code === 200 ? response.data.data : null;
    } catch (error) {
      return handleApiError(error, '获取学习统计失败');
    }
  }

  /**
   * 获取用户统计
   */
  static async getUserStatistics() {
    try {
      const response = await getUserStatistics();
      return response.data.code === 200 ? response.data.data : null;
    } catch (error) {
      return handleApiError(error, '获取用户统计失败');
    }
  }
}

// ==================== 文件上传服务 ====================

export class UploadService {
  /**
   * 上传文件
   */
  static async uploadFile(file: File, onProgress?: (progress: number) => void) {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await uploadFile(formData);

      if (response.data.code === 200) {
        return response.data.data;
      } else {
        showToast(response.data.message || '上传失败');
        return null;
      }
    } catch (error) {
      return handleApiError(error, '文件上传失败');
    }
  }

  /**
   * 创建音频Blob
   */
  static createAudioBlob(audioData: ArrayBuffer, mimeType: string = 'audio/wav'): Blob {
    return new Blob([audioData], { type: mimeType });
  }

  /**
   * 创建视频Blob
   */
  static createVideoBlob(videoData: ArrayBuffer, mimeType: string = 'video/mp4'): Blob {
    return new Blob([videoData], { type: mimeType });
  }
}
